
import VueRouter from 'vue-router';
import routes from './routes'
import store from '@/store';
//1、先把VueRouter原型对象的push，保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.Replace;
//2、重写push|replace
//第一个参数：告诉原来的push，跳转的目标位置和传递了哪些参数
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}
const router = new VueRouter({
    routes,
    scrollBehavior() {
        // 始终滚动到顶部
        return { y: 0 }
    },
})
router.beforeEach(async (to, from, next) => {
    //用户登录过，一定会有token信息
    let token = store.state.user.token
    //用户登录状态，一定会有用户名字
    let name = store.state.user.userInfo.loginName
    if (token) {
        //当用户处于登录状态时，不能进入登录组件和注册组件
        if (to.path == '/Login' || to.path == '/register') {
            next('/home')
        } else {
            if (name) {
                //有用户信息，想去那就去哪
                next()
            } else {
                //当用户重新刷新页面时，vuex里的token丢失，重新发向服务器请求获取用户token
                try {
                    await store.dispatch('user/getUserInfo')
                    next()
                } catch (error) {
                    //如果请求失败，一般token过期，退出登录操作后重新登录获取token
                    await store.dispatch('user/logout')
                    //回到登录界面
                    next('/Login')
                }
            }
        }
    } else {
        //未登录访问，交易相关（trade）、支付相关（pay，paysuccess)、用户中心（center）相关跳转到  登录页面
        let path = to.path
        if (path.indexOf('/Trade') != -1 || path.indexOf('/pay') != -1 || path.indexOf('/Center') != -1) {
            //未登录时，想去上面的地址时，把地址添加到query，在登录组件获取query，等用户登录后自动跳转到上面的地址
            next('/Login?redirect=' + path)
        } else {
            next()
        }
    }
})
export default router